package demo;
import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class UseThreadPool {
    static class ForeverTask implements Runnable{
        @Override
        public void run() {
           try{
               while(true){
                  TimeUnit.DAYS.sleep(365);
               }
           }catch(InterruptedException ignored){

           }
        }
    }

    public static void main(String[] args) {

        BlockingQueue<Runnable> queue=new ArrayBlockingQueue<Runnable>(4);
        ThreadPoolExecutor pool=new ThreadPoolExecutor(2,10,20,TimeUnit.SECONDS,queue);
        Scanner sc=new Scanner(System.in);

        for(int i=0;true;i++) {
            System.out.println("按一次回车，就提交一次任务:");
            sc.nextLine();
            ForeverTask foreverTask=new ForeverTask();
            //设定阻塞队列容量上限为4
            //最大线程数：10
            //所以最后只能最多提交14次任务
            //最后main线程挂了以后，线程池里的线程还在继续
            //因为线程池的线程默认为前台线程
            System.out.println("提交任务数:"+i);
            pool.execute(foreverTask);
        }
        }
    }

